package grimbo.goodwinfooty.server;

import grimbo.goodwinfooty.server.jdo.PMF;

import java.io.IOException;
import java.security.Principal;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class ClearDataServlet extends HttpServlet {
	private static final String CNAME = ClearDataServlet.class.getName();
	private static final Logger log = Logger.getLogger(CNAME);

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		final String MNAME = "doGet(HttpServletRequest, HttpServletResponse)";
		final boolean DEBUG = log.isLoggable(Level.FINE);
		log.entering(CNAME, MNAME);

		process(req, resp);

		log.exiting(CNAME, MNAME);
	}

	private void process(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();

		String thisURL = req.getRequestURI();
		Principal principal = req.getUserPrincipal();
		if (null == principal) {
			res.sendRedirect(userService.createLoginURL(thisURL));
			return;
		}

		System.out.println(principal.getName());

		res.setContentType("text/plain");

		String[] queries = createQueries(req);

		if ((null != queries) || (queries.length > 0)) {
			clearUsingJDO(queries);
		}
	}

	private String[] createQueries(HttpServletRequest req) {
		String[] queries = req.getParameterValues("q");
		return queries;
	}

	private void clearUsingJDO(String[] queries) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			for (int i = 0; i < queries.length; i++) {
				String q = queries[i];
				if ((null == q) || ("".equals(q.trim()))) {
					throw new IllegalArgumentException(
							"Query string cannot be null or empty.");
				}
				Query query = pm.newQuery(q);
				List list = (List) query.execute();
				log.info("found " + (null != list ? list.size() : "null")
						+ " items for query " + q + ".");
				pm.deletePersistentAll(list);
			}
		} finally {
			pm.close();
		}
	}
}
